---
import { Code } from "astro/components";
import { JSONContent } from "../api";
import { createContentTransformer } from "../transformers";

interface Props extends JSONContent {}

const { type, attrs, content } = Astro.props;
const render = (config: Parameters<typeof createContentTransformer<object | string>>[0]) => {
  const htmlTransformer = createContentTransformer<object | string>(config);

  return htmlTransformer({ type, attrs, content });
};
---

{
  render({
    applyInlineFormatting(type, attrs, content) {
      switch (type) {
        case "link":
          return <a href={`${attrs.href}`}>{content}</a>;
        case "bold":
          return <strong>{content}</strong>;

        case "code":
          return <code>{content}</code>;

        case "italic":
          return <em>{content}</em>;

        case "strike":
          return <s>{content}</s>;

        case "highlight":
          return <mark>{content}</mark>;

        case "superscript":
          return <sup>{content}</sup>;

        case "subscript":
          return <sub>{content}</sub>;

        default:
          return content;
      }
    },
    transformNode(type, attrs, content, ancestors) {
      switch (type) {
        case "paragraph":
          if (["tableCell", "tableHeader"].includes(ancestors[ancestors.length - 1].type)) {
            return content;
          }

          return <p>{content}</p>;
        case "hardBreak":
          return <br />;
        case "heading":
          const Component = `h${attrs?.level || 1}`;

          return <Component>{content}</Component>;
        case "blockquote":
          return <blockquote>{content}</blockquote>;
        case "image":
          return <img src={`${attrs?.src}`} alt={`${attrs?.alt}`} />;
        case "codeBlock":
          return <Code code={`${content}`} lang={`${attrs?.lang}` as any} />;
        case "embed":
          return <iframe src={`${attrs?.src}`} data-type={`${attrs?.embed}`} />;
        case "bulletList":
          return <ul>{content}</ul>;
        case "orderedList":
          return <ol>{content}</ol>;
        case "taskList":
          return <ul data-type="taskList">{content}</ul>;
        case "taskItem":
          return (
            <li data-type="taskItem">
              <label>
                <input type="checkbox" checked={`${attrs?.checked}`} />
              </label>
              <div>{content}</div>
            </li>
          );
        case "listItem":
          return <li>{content}</li>;
        case "horizontalRule":
          return <hr />;
        case "table":
          return <table>{content}</table>;
        case "tableRow":
          return <tr>{content}</tr>;
        case "tableCell":
          return <td>{content}</td>;
        case "tableHeader":
          return <th>{content}</th>;
        default:
          return content;
      }
    },
    processOutput(nodes) {
      return nodes;
    }
  })
}
